package org.amse.mARICa;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFrame;
import org.amse.mARICa.view.MainFrame;

public class Main {

	private static Tournament myTour;

	public static void main(String[] args) {
		Logger log = Logger.getInctanse();
		if (args.length != 0){
			for( int i = 0; i < args.length; i++){
				if (args[i].equals("log")){				
					log.setLog(true);				
				}else if (args[i].equals("tour")){
					String fileName;
					if (i+1 >= args.length){
						System.out.println("Filename with settings for Tournament isn't");
						return;
					}
					fileName = args[++i];
					myTour = createTournament(fileName);
				}
			}
		}
		if (myTour != null){
			myTour.startTournament();
		}else{
			JFrame frame = new MainFrame ();
			frame.setLocation(50,50);
			frame.setResizable(false);
			frame.setSize(450,200);
			frame.setVisible(true);
		}
		
	}

	private static Tournament createTournament(String fileName) {
		Tournament tour = null;
		int countGames = 1, countPots = 6, countBeans = 4;		
		String DOWNname = "", UPname = "";
		int DOWNlevel = 2, UPlevel = 2;
		boolean DOWNrand = false, UPrand = false;
		BufferedReader buf;
		String s;
		boolean isStep = false;
		try {
			buf = new BufferedReader (new FileReader(fileName));			
			while ((s = buf.readLine()) != null){
				if (s.startsWith("countGames ")){
					countGames = Integer.valueOf(s.substring("countGames ".length()));
				}if (s.startsWith("countPots ")){
					countPots = Integer.valueOf(s.substring("countPots ".length()));
				}if (s.startsWith("countBeans ")){
					countBeans = Integer.valueOf(s.substring("countBeans ".length()));
				}if (s.startsWith("DOWN name ")){
					DOWNname = s.substring("DOWN name ".length());
				}if (s.startsWith("DOWN level ")){
					DOWNlevel = Integer.valueOf(s.substring("DOWN level ".length()));
				}if (s.startsWith("DOWN rand ")){
					DOWNrand = Boolean.valueOf(s.substring("DOWN rand ".length()));
				}if (s.startsWith("UP name ")){
					UPname = s.substring("UP name ".length());
				}if (s.startsWith("UP level ")){
					UPlevel = Integer.valueOf(s.substring("UP level ".length()));
				}if (s.startsWith("UP rand ")){
					UPrand = Boolean.valueOf(s.substring("UP rand ".length()));
				}if (s.startsWith("step")){
					isStep = true;
				}			
			}
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			return null;
		} catch (NumberFormatException e) {
			System.out.println(e.getMessage());
			return null;
		} catch (IOException e) {
			System.out.println(e.getMessage());
			return null;
		}
		tour = new Tournament(countGames, countPots, countBeans);
		tour.setPlayer(DOWNname, DOWNlevel, DOWNrand);
		tour.setPlayer(UPname, UPlevel, UPrand);
		tour.setStep(isStep);
		return tour;
	}

}
